package com.centaline.androidsalesblog.activities.sale;

import android.content.Intent;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviParaOption;
import com.bumptech.glide.DrawableRequestBuilder;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.activities.ImgListBrowseActivity;
import com.centaline.androidsalesblog.activities.map.AroundMapActivity;
import com.centaline.androidsalesblog.activities.mine.LoginActivity;
import com.centaline.androidsalesblog.activities.newest.NearbyNewEstListActivity;
import com.centaline.androidsalesblog.api.newest.NewEstListApi;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.api.sale.EstEstateDetailApi;
import com.centaline.androidsalesblog.api.sale.PostInternalApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.AppNameType;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.constants.SourceType;
import com.centaline.androidsalesblog.constants.SprfConstant;
import com.centaline.androidsalesblog.events.MineInfoUpdate;
import com.centaline.androidsalesblog.iml.ImgViewPagerClickListener;
import com.centaline.androidsalesblog.model.businissobject.CollectInfoBo;
import com.centaline.androidsalesblog.model.businissobject.EsfImgBo;
import com.centaline.androidsalesblog.model.businissobject.EstateDataModelBo;
import com.centaline.androidsalesblog.model.businissobject.EstateInfoBo;
import com.centaline.androidsalesblog.model.businissobject.EstateOtherInfoBo;
import com.centaline.androidsalesblog.model.businissobject.PostInternalBo;
import com.centaline.androidsalesblog.model.businissobject.SaleEstateBo;
import com.centaline.androidsalesblog.model.businissobject.ShareBo;
import com.centaline.androidsalesblog.model.databaseobject.BizUnitDo;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.responseobject.CollectInfoListRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateDetailRo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centaline.androidsalesblog.model.responseobject.NewEstListRo;
import com.centaline.androidsalesblog.model.responseobject.PostInternalRo;
import com.centaline.androidsalesblog.model.responseobject.SimpleUserCenterRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.rx.request.RxRequest;
import com.centaline.androidsalesblog.utils.BdMapUtil;
import com.centaline.androidsalesblog.utils.DateUtil;
import com.centaline.androidsalesblog.utils.PriceUtil;
import com.centaline.androidsalesblog.utils.ResponseCheck;
import com.centaline.androidsalesblog.widgets.DetailImgLayout;
import com.centaline.androidsalesblog.widgets.ShareDialog;
import com.centaline.androidsalesblog.widgets.chart.SaleLineChart;
import com.centaline.androidsalesblog.widgets.dropdown.SpecialLoadView;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.SprfUtil;
import com.centanet.framework.widget.AbstractSpecialLoadView;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 小区详情
 */
public class EsfEstateDetailActivity extends BaseActivity implements View.OnClickListener {

    /*UI*/
    private SpecialLoadView specialLoadView;
    private AppCompatTextView atv_sale_count, atv_rent_count, atv_price_avg, atv_house_type_esf,
            atv_floor_ratio, atv_green_ratio, atv_build_year, atv_park, atv_mgt_price, atv_mgt_company,
            atv_developer, atv_feature, atv_address, atv_map_name, atv_nav, atv_num_price, atv_num_new_est;
    private ImageView img_arrow_address, img_map;
    private DetailImgLayout detailImgLayout;
    private ViewStub vs_sale_metro, vs_sale_school, vs_line;
    private RelativeLayout rl_deal_history, rl_esf_of_price, rl_new_est, rl_map;

    private DrawableRequestBuilder<String> requestBuilder;
    private EstateDataModelBo estateDataModelBo;
    private ArrayList<EsfImgBo> esfImgBos = new ArrayList<>();
    private ArrayList<String> imgList = new ArrayList<>();
    private String cestCode;

    private boolean collect;//是否收藏
    private String collectId;
    private LocationClient locationClient;
    private boolean newPropEnable;//新盘是否可用

    private String shareUrl;
    private ShareDialog shareDialog;
    private String schoolToEastate;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_esf_estate;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        specialLoadView = (SpecialLoadView) findViewById(R.id.specialLoadView);
        atv_sale_count = (AppCompatTextView) findViewById(R.id.atv_sale_count);
        atv_rent_count = (AppCompatTextView) findViewById(R.id.atv_rent_count);
        atv_price_avg = (AppCompatTextView) findViewById(R.id.atv_price_avg);
        atv_house_type_esf = (AppCompatTextView) findViewById(R.id.atv_house_type_esf);
        atv_floor_ratio = (AppCompatTextView) findViewById(R.id.atv_floor_ratio);
        atv_green_ratio = (AppCompatTextView) findViewById(R.id.atv_green_ratio);
        atv_build_year = (AppCompatTextView) findViewById(R.id.atv_build_year);
        atv_park = (AppCompatTextView) findViewById(R.id.atv_park);
        atv_mgt_price = (AppCompatTextView) findViewById(R.id.atv_mgt_price);
        atv_mgt_company = (AppCompatTextView) findViewById(R.id.atv_mgt_company);
        atv_developer = (AppCompatTextView) findViewById(R.id.atv_developer);
        atv_feature = (AppCompatTextView) findViewById(R.id.atv_feature);
        atv_address = (AppCompatTextView) findViewById(R.id.atv_address);
        atv_nav = (AppCompatTextView) findViewById(R.id.atv_nav);
        atv_map_name = (AppCompatTextView) findViewById(R.id.atv_map_name);
        atv_num_price = (AppCompatTextView) findViewById(R.id.atv_num_price);
        atv_num_new_est = (AppCompatTextView) findViewById(R.id.atv_num_new_est);
        img_arrow_address = (ImageView) findViewById(R.id.img_arrow_address);
        img_map = (ImageView) findViewById(R.id.img_map);
        detailImgLayout = (DetailImgLayout) findViewById(R.id.detailImgLayout);
        vs_sale_metro = (ViewStub) findViewById(R.id.vs_sale_metro);
        vs_sale_school = (ViewStub) findViewById(R.id.vs_sale_school);
        vs_line = (ViewStub) findViewById(R.id.vs_line);
        rl_deal_history = (RelativeLayout) findViewById(R.id.rl_deal_history);
        rl_esf_of_price = (RelativeLayout) findViewById(R.id.rl_esf_of_price);
        rl_new_est = (RelativeLayout) findViewById(R.id.rl_new_est);
        rl_map = (RelativeLayout) findViewById(R.id.rl_map);
    }

    @Override
    protected void initViews() {
        requestBuilder = GlideLoad.init(this);
        detailImgLayout.setRequestBuilder(requestBuilder);
        detailImgLayout.setImgViewPagerClickListener(new ImgViewPagerClickListener() {
            @Override
            public void imgItemClick(int position) {
                startActivity(new Intent(EsfEstateDetailActivity.this, ImgListBrowseActivity.class)
                        .putExtra(ExtraConstant.IMG_LIST, imgList)
                        .putExtra(ExtraConstant.IMG_POS, position));
            }
        });
        specialLoadView.setLoadStatusListener(new AbstractSpecialLoadView.LoadStatusListener() {
            @Override
            public void load() {
                mainRequest();
            }
        });

        cestCode = getIntent().getStringExtra(ExtraConstant.CestCode);

        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        cancelLoadingDialog();
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                NaviParaOption naviParaOption = new NaviParaOption();
                                naviParaOption.startPoint(new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()))
                                        .endPoint(new LatLng(estateDataModelBo.getSaleEstateBo().getLat(),
                                                estateDataModelBo.getSaleEstateBo().getLng()));
                                BaiduMapNavigation.openBaiduMapNavi(naviParaOption, EsfEstateDetailActivity.this);
                                break;
                            default:
                                snack("定位失败");
                                break;
                        }
                    }
                });
        atv_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });

        bizUnit();
        mainRequest();
    }

    private void mainRequest() {
        EstEstateDetailApi estEstateDetailApi = new EstEstateDetailApi(EsfEstateDetailActivity.class, EsfEstateDetailRo.class,
                new IResponseListener<EsfEstateDetailRo>() {
                    @Override
                    public void onResponse(EsfEstateDetailRo esfEstateDetailRo) {
                        if (ResponseCheck.check(esfEstateDetailRo) &&
                                esfEstateDetailRo.getEsfResultBo() != null &&
                                esfEstateDetailRo.getEsfResultBo().getEstateDataModelBos() != null) {
                            specialLoadView.loadSuccess();
                            estateDataModelBo = esfEstateDetailRo.getEsfResultBo().getEstateDataModelBos().get(0);
                            esfImgBos.clear();
                            esfImgBos.addAll(esfEstateDetailRo.getEsfResultBo().getEsfImgBos());
                            detailImgLayout.setTencentVistaUrl(esfEstateDetailRo.getEsfResultBo().getTencentVistaUrl());
                            schoolToEastate = esfEstateDetailRo.getEsfResultBo().getSchoolToEstate();
                            invalidateOptionsMenu();
                            setData();
                            otherRequest();
                        } else {
                            specialLoadView.loadError();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        specialLoadView.loadError();
                    }
                });
        estEstateDetailApi.setCestCode(cestCode);
        estEstateDetailApi.startRequest();

    }

    private void otherRequest() {
        //房价走势
        PostInternalApi postInternalApi = new PostInternalApi(EsfEstateDetailActivity.class, PostInternalRo.class,
                new IResponseListener<PostInternalRo>() {
                    @Override
                    public void onResponse(PostInternalRo postInternalRo) {
                        if (postInternalRo != null) {
                            ArrayList<PostInternalBo> postInternalBos = postInternalRo.getList();
                            if (postInternalBos != null &&
                                    postInternalBos.size() > 0) {
                                boolean show = false;
                                for (PostInternalBo postInternalBo : postInternalBos) {
                                    if (postInternalBo != null &&
                                            "estate".equalsIgnoreCase(postInternalBo.getType()) &&
                                            postInternalBo.getDealListBos() != null &&
                                            postInternalBo.getDealListBos().size() > 2) {
                                        show = true;
                                    }
                                }
                                if (show && vs_line != null) {
                                    rl_deal_history.setVisibility(View.VISIBLE);
                                    vs_line.inflate();
                                    SaleLineChart saleLineChart = (SaleLineChart) findViewById(R.id.saleLineChart);
                                    if (saleLineChart != null) {
                                        saleLineChart.setPostInternalBos(estateDataModelBo.getSaleEstateBo().getC_estate(),
                                                postInternalBos);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
        postInternalApi.setCestcode(cestCode);
        postInternalApi.setGscopeid(String.valueOf(estateDataModelBo.getSaleEstateBo().getGScopeId()));
        postInternalApi.startRequest();

        String min = String.format(Locale.CHINA, "%.0f", estateDataModelBo.getEstateOtherInfoBo().getCestAvgPrice() * 0.9);
        String max = String.format(Locale.CHINA, "%.0f", estateDataModelBo.getEstateOtherInfoBo().getCestAvgPrice() * 1.1);

        /**
         * 同价位小区
         */
        if (estateDataModelBo.getSaleEstateBo() != null &&
                estateDataModelBo.getSaleEstateBo().getLat() != 0 && estateDataModelBo.getSaleEstateBo().getLng() != 0) {
            EsfEstateListApi esfEstateListApi = new EsfEstateListApi(EsfEstateDetailActivity.class,
                    EsfEstateListRo.class,
                    new IResponseListener<EsfEstateListRo>() {
                        @Override
                        public void onResponse(EsfEstateListRo esfEstateListRo) {
                            if (esfEstateListRo.getTotal() > 0) {
                                rl_esf_of_price.setVisibility(View.VISIBLE);
                                atv_num_price.setText(String.format(Locale.CHINA, "%d个", esfEstateListRo.getTotal()));
                            }
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
            esfEstateListApi.setLatLng(
                    new LatLng(estateDataModelBo.getSaleEstateBo().getLat(), estateDataModelBo.getSaleEstateBo().getLng()));
            esfEstateListApi.setType("F");
            esfEstateListApi.setPosttype("s");
            esfEstateListApi.setRound("1000");
            esfEstateListApi.setPageCount(0);
            esfEstateListApi.setMin(min);
            esfEstateListApi.setMax(max);
            esfEstateListApi.startRequest();
        }


        /**
         * 同价位新盘
         */
        if (newPropEnable &&
                estateDataModelBo.getSaleEstateBo() != null &&
                estateDataModelBo.getSaleEstateBo().getLat() != 0 && estateDataModelBo.getSaleEstateBo().getLng() != 0) {
            NewEstListApi newEstListApi = new NewEstListApi(EsfEstateDetailActivity.class,
                    NewEstListRo.class,
                    new IResponseListener<NewEstListRo>() {
                        @Override
                        public void onResponse(NewEstListRo newEstListRo) {
                            if (newEstListRo.getTotal() > 0) {
                                rl_new_est.setVisibility(View.VISIBLE);
                                atv_num_new_est.setText(String.format(Locale.CHINA, "%d个", newEstListRo.getTotal()));
                            }
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
            newEstListApi.setMinAveragePrice(min);
            newEstListApi.setMaxAveragePrice(max);
            newEstListApi.startRequest();
        }

        collectStatus();
    }

    private void setData() {
        final SaleEstateBo saleEstateBo = estateDataModelBo.getSaleEstateBo();
        final EstateOtherInfoBo estateOtherInfoBo = estateDataModelBo.getEstateOtherInfoBo();
        final EstateInfoBo estateInfoBo = estateDataModelBo.getEstateInfoBo();
        setToolbarTitle(String.format(Locale.CHINA, "%s%s", saleEstateBo.getC_estate(), saleEstateBo.getC_phase()));
        atv_sale_count.setText(String.format(Locale.CHINA, "%d套", estateOtherInfoBo.getSPostNum()));
        atv_rent_count.setText(String.format(Locale.CHINA, "%d套", estateOtherInfoBo.getRPostNum()));
        atv_price_avg.setText(PriceUtil.esfSaleAvgPrice(estateOtherInfoBo.getCestAvgPrice()));
        atv_house_type_esf.setText(estateOtherInfoBo.getPropertyus());
        atv_floor_ratio.setText(estateInfoBo.getFloorRatio() == 0 ? "暂无资料" :
                String.format(Locale.CHINA, "%.2f", estateInfoBo.getFloorRatio()));
        atv_green_ratio.setText(estateInfoBo.getGreenRatio() == 0 ? "暂无资料" :
                String.format(Locale.CHINA, "%.0f%%", estateInfoBo.getGreenRatio() * 100));
        String year = TextUtils.isEmpty(saleEstateBo.getOpdate()) ? "" :
                DateUtil.format(saleEstateBo.getOpdate(), DateUtil.FORMAT1, DateUtil.FORMAT3);
        if (TextUtils.isEmpty(year) ||
                "1900".equals(year)) {
            atv_build_year.setText("暂无资料");
        } else {
            atv_build_year.setText(String.format(Locale.CHINA, "%s年",
                    year));
        }
        atv_park.setText(TextUtils.isEmpty(estateInfoBo.getCarPark()) ? "暂无资料" :
                estateInfoBo.getCarPark());
        atv_mgt_price.setText(TextUtils.isEmpty(estateInfoBo.getMgt_price()) ?
                "暂无" :
                String.format(Locale.CHINA, "%s元/平/月", estateInfoBo.getMgt_price()));
        atv_mgt_company.setText(TextUtils.isEmpty(estateInfoBo.getPc_mgt_com()) ? "暂无资料" :
                estateInfoBo.getPc_mgt_com());
        atv_developer.setText(TextUtils.isEmpty(estateInfoBo.getPc_dev()) ? "暂无资料" :
                estateInfoBo.getPc_dev());
        atv_feature.setText(TextUtils.isEmpty(estateOtherInfoBo.getCestFeature()) ?
                "暂无资料" : estateOtherInfoBo.getCestFeature());
        atv_address.setText(String.format("%s-%s  %s", estateDataModelBo.getRegionName(),
                estateDataModelBo.getGScopeName(), saleEstateBo.getPc_addr()));
        detailImgLayout.setTitle(estateOtherInfoBo.getCestTitle());
        for (EsfImgBo esfImgBo : esfImgBos) {
            imgList.add(esfImgBo.getText());
        }
        detailImgLayout.setImgList(imgList);

        if (!TextUtils.isEmpty(estateInfoBo.getRailway()) &&
                vs_sale_metro != null) {
            vs_sale_metro.inflate();
            AppCompatTextView atv_metro_info = (AppCompatTextView) findViewById(R.id.atv_metro_info);
            if (atv_metro_info != null) {
                atv_metro_info.setText(String.format(Locale.CHINA, "%s", estateInfoBo.getRailway()));
            }
        }

        if (!TextUtils.isEmpty(schoolToEastate) &&
                vs_sale_school != null) {
            vs_sale_school.inflate();
            AppCompatTextView atv_school_info = (AppCompatTextView) findViewById(R.id.atv_school_info);
            if (atv_school_info != null) {
                atv_school_info.setText(schoolToEastate);
            }
        }
        if (saleEstateBo.getLng() != 0 &&
                saleEstateBo.getLat() != 0) {
            img_arrow_address.setVisibility(View.VISIBLE);
            atv_nav.setVisibility(View.VISIBLE);
            atv_map_name.setText(saleEstateBo.getC_estate());
            rl_map.setVisibility(View.VISIBLE);
            GlideLoad.load(new GlideLoad.Builder(requestBuilder,
                    BdMapUtil.getBaiduMapImgUrl(saleEstateBo.getLng(), saleEstateBo.getLat()))
                    .placeHolder(R.drawable.ic_banner)
                    .error(R.drawable.ic_banner)
                    .openWifiSwitch()
                    .into(img_map));
        }

        /*数据库保存*/
        EsfEstateDo esfEstateDo = new EsfEstateDo();
        esfEstateDo.setName(estateOtherInfoBo.getC_Estate());
        esfEstateDo.setSaleCount(estateOtherInfoBo.getSPostNum());
        esfEstateDo.setRentCount(estateOtherInfoBo.getRPostNum());
        esfEstateDo.setPc_Addr(saleEstateBo.getPc_addr());
        esfEstateDo.setCestAvgPrice(estateOtherInfoBo.getCestAvgPrice());
        esfEstateDo.setCestAvgPriceR(estateOtherInfoBo.getCestAvgPriceR());
        esfEstateDo.setCestCode(cestCode);
        esfEstateDo.setLat(saleEstateBo.getLat());
        esfEstateDo.setLng(saleEstateBo.getLng());
        esfEstateDo.setDefaultImg(imgList.size() == 0 ? "" : imgList.get(0));
        esfEstateDo.setRegion(estateDataModelBo.getRegionName());
        esfEstateDo.setScope(estateDataModelBo.getGScopeName());
        RxDataBase.fpHistorySave(2, cestCode, esfEstateDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Void>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {

                    }
                });
    }

    /**
     * 开始定位
     */
    private void startLocation() {
        showLoadingDialog();
        locationClient.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_sale:
                startActivity(new Intent(this, EsfSaleListActivity.class)
                        .putExtra(ExtraConstant.CestCode, cestCode)
                        .putExtra(BaseActivity.TITLE_ACTIVITY, estateDataModelBo.getSaleEstateBo().getC_estate()));
                break;
            case R.id.ll_rent:
                startActivity(new Intent(this, EsfRentListActivity.class)
                        .putExtra(ExtraConstant.CestCode, cestCode)
                        .putExtra(BaseActivity.TITLE_ACTIVITY, estateDataModelBo.getSaleEstateBo().getC_estate()));
                break;
            case R.id.rl_deal_history:
                startActivity(new Intent(this, EsfDealHistoryActivity.class)
                        .putExtra(ExtraConstant.CestCode, cestCode));
                break;
            case R.id.rl_address://地图
            case R.id.img_map:
                if (estateDataModelBo.getSaleEstateBo() == null ||
                        estateDataModelBo.getSaleEstateBo().getLat() == 0 || estateDataModelBo.getSaleEstateBo().getLng() == 0) {
                    snack("地理位置获取失败");
                } else {
                    startActivity(new Intent(this, AroundMapActivity.class)
                            .putExtra(ExtraConstant.LatLng, new LatLng(estateDataModelBo.getSaleEstateBo().getLat(),
                                    estateDataModelBo.getSaleEstateBo().getLng()))
                            .putExtra(ExtraConstant.MAP_NAME, estateDataModelBo.getSaleEstateBo().getC_estate()));
                }
                break;
            case R.id.rl_esf_of_price:
                startActivity(new Intent(this, EsfEstateListOfPriceActivity.class)
                        .putExtra(ExtraConstant.LatLng,
                                new LatLng(estateDataModelBo.getSaleEstateBo().getLat(), estateDataModelBo.getSaleEstateBo().getLng()))
                        .putExtra(ExtraConstant.Price, estateDataModelBo.getEstateOtherInfoBo().getCestAvgPrice()));
                break;
            case R.id.rl_new_est:
                startActivity(new Intent(this, NearbyNewEstListActivity.class)
                        .putExtra(BaseActivity.TITLE_ACTIVITY, "同价位新盘")
                        .putExtra(ExtraConstant.Price, estateDataModelBo.getEstateOtherInfoBo().getCestAvgPrice()));
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_collect_share, menu);
        MenuItem shareItem = menu.findItem(R.id.action_share);
        shareItem.setVisible(estateDataModelBo != null && !TextUtils.isEmpty(shareUrl));
        MenuItem collectItem = menu.findItem(R.id.action_collect);
        collectItem.setVisible(estateDataModelBo != null);
        collectItem.setIcon(collect ? R.drawable.ic_collected : R.drawable.ic_uncollected);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (R.id.action_collect == item.getItemId()) {
            collect();
        } else if (R.id.action_share == item.getItemId()) {
            if (shareDialog == null) {
                ShareBo shareBo = new ShareBo(2);
                shareBo.setHouseName(estateDataModelBo.getSaleEstateBo().getC_estate());
                shareBo.setRegionGscop(String.format(Locale.CHINA, "%s-%s",
                        estateDataModelBo.getRegionName(), estateDataModelBo.getGScopeName()));
                shareBo.setHouseDecription(estateDataModelBo.getEstateOtherInfoBo().getCestTitle());
                shareBo.setAvgPrice(String.format(Locale.CHINA, "%.0f元/平",
                        estateDataModelBo.getEstateOtherInfoBo().getCestAvgPrice()));
                shareBo.setHouseUrl(shareUrl.replace("{0}", cestCode));
                shareBo.setImageUrl(imgList.size() > 0 ? imgList.get(0) : "");
                shareDialog = new ShareDialog(this, shareBo);
            }
            shareDialog.show();
            baiduEvent("J3_1_Type");
        }
        return super.onOptionsItemSelected(item);
    }

    private void collect() {
        if (AppConstant.IsLogin) {
            if (collect) {
                RxRequest.cancelCollect(EsfEstateDetailActivity.class, collectId)
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = false;
                                    EventBus.getDefault().post(new MineInfoUpdate(13));
                                    invalidateOptionsMenu();
                                    snack(R.string.collect_cancel);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            } else {
                RxRequest.addCollect(EsfEstateDetailActivity.class, AppNameType.ESF, SourceType.XIAOQU, collectId, cestCode,
                        String.format(Locale.CHINA, "%s%s?cestCode=%s", AppConstant.SaleUrl, "EsfEstate", cestCode))
                        .compose(this.<SimpleUserCenterRo>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Action1<SimpleUserCenterRo>() {
                            @Override
                            public void call(SimpleUserCenterRo simpleUserCenterRo) {
                                if (0 == simpleUserCenterRo.getResultNo()) {
                                    collect = true;
                                    if (0 != simpleUserCenterRo.getResult()) {
                                        collectId = String.valueOf(simpleUserCenterRo.getResult());
                                    }
                                    EventBus.getDefault().post(new MineInfoUpdate(13));
                                    invalidateOptionsMenu();
                                    SprfUtil.setInt(EsfEstateDetailActivity.this,
                                            String.format("%s_%s", SprfConstant.COLLECT_POSITION, AppConstant.CityCode), 13);
                                    snack(R.string.collect_success);
                                } else {
                                    snack(simpleUserCenterRo.getMessage());
                                    collectStatus();
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                netWorkUnable();
                            }
                        });
            }
        } else {
            startActivityForResult(new Intent(this, LoginActivity.class), CommonConstant.REQ_COLLECT);
        }
    }

    /**
     * 收藏状态
     */
    private void collectStatus() {
        if (AppConstant.IsLogin) {
            RxRequest.collectStatus(EsfEstateDetailActivity.class, cestCode,
                    String.format(Locale.CHINA, "%s%s?cestCode=%s", AppConstant.SaleUrl, "EsfEstate", cestCode))
                    .compose(this.<CollectInfoListRo>bindUntilEvent(ActivityEvent.DESTROY))
                    .subscribe(new Action1<CollectInfoListRo>() {
                        @Override
                        public void call(CollectInfoListRo collectInfoListRo) {
                            final ArrayList<CollectInfoBo> temp = collectInfoListRo.getList();
                            if (temp != null &&
                                    temp.size() > 0) {
                                collectId = String.valueOf(temp.get(0).getCollectID());
                                collect = !temp.get(0).isDel();
                            } else {
                                collect = false;
                            }
                            invalidateOptionsMenu();
                        }
                    });
        }
    }

    /**
     * 获取配置
     */
    private void bizUnit() {
        RxDataBase.getBizUnit()
                .compose(this.<BizUnitDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<BizUnitDo>() {
                    @Override
                    public void call(BizUnitDo bizUnitDo) {
                        invalidateOptionsMenu();
                        newPropEnable = bizUnitDo.isEnableNewprop();
                        shareUrl = bizUnitDo.getShareXiaoqu();
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CommonConstant.REQ_COLLECT:
                    collect();
                    break;
                default:
                    break;
            }
        }
    }
}
